var events=require('events');
var fs=require('fs');
var util=require('util');

function Watcher(watchDir,processDir){
    this.watchDir  = watchDir;
    this.processDir = processDir;
}
util.inherits(Watcher,events);

Watcher.prototype.start= function () {
    var watcher=this;
    fs.readdir(this.watchDir, function (err, files) {
        if(err)throw err;
        for(var i in files){
            watcher.watch(files[i]);
        }
        console.log('Watch:',new Date());
    });
}

Watcher.prototype.watch= function (file) {
    var watcher=this;
    fs.watchFile(this.watchDir+'/'+file, function (curr,prev) {
        console.log('curr:',curr);
        watcher.emit('process');
    });
}

var watcher=new Watcher('./watch','./done');
watcher.on('process', function (file) {
    var watchFile=this.watchDir+'/'+file;
    var processFile=this.processDir+'/'+file;
    fs.open(processFile,'w', function (err,fd) {
        if(err)throw err;
        fs.readFile(watchFile, function (err, data) {
            if(err)throw err;
            var buffer=data;
            console.log('buffer:',data);
            fs.write(fd,buffer,0,buffer.length,0, function (err) {
                if(err)throw err;
                console.log(watchFile,'changed!!');
            });
        });
    });
});
watcher.start();
